package com.kma.ncpractice2013.auth;

import com.kma.ncpractice2013.dao.UserDAO;
import com.kma.ncpractice2013.model.User;

import javax.naming.NamingException;
import javax.xml.bind.DatatypeConverter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.UUID;

/**
 * User: Viktor
 * Date: 10/11/13
 */
public class Crypto
{
	public static final int INVALID_CREDENTIALS = 100;
	public static final int ACCOUNT_BLOCKED = 90;
	public static String getHash(String salt, String pass, String algorithm)
    {

		MessageDigest messageDigest = null;
	    try
	    {
		    messageDigest = MessageDigest.getInstance(algorithm);
	    } catch (NoSuchAlgorithmException e)
	    {
		    e.printStackTrace();
	    }


	    try
	    {
		    messageDigest.update((salt + pass).getBytes("UTF-8"));
	    } catch (UnsupportedEncodingException e)
	    {
		    e.printStackTrace();
	    }
	    return DatatypeConverter.printHexBinary(messageDigest.digest());


	}
	public static String generateSalt()
	{
		SecureRandom secureRandom = null;
		try
		{
			secureRandom = SecureRandom.getInstance("SHA1PRNG");
		} catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}
		secureRandom.setSeed(System.currentTimeMillis());
		byte[] salt = new byte[32];

		secureRandom.nextBytes(salt);
		return DatatypeConverter.printHexBinary(salt);
	}
	public static int getAccessLevel(String uname, String pass)
	{


		UserDAO userDAO = new UserDAO();
		User user = userDAO.getByLogin(uname);


		if(user!=null)
		{
			String salt = user.getSalt();

			user = userDAO.getByLogPass(uname, Crypto.getHash(salt, pass, "SHA-256"));
			if (user!=null)
				if (user.getBlocked()!=1)
					return user.getAccessLevelId().getValue();
				else return ACCOUNT_BLOCKED;
			else return INVALID_CREDENTIALS;
		}
		else
			return INVALID_CREDENTIALS;

	}
}
